import { Form, Card, Button, Divider, message } from 'antd';
import React, { Component, Fragment } from 'react';
import { FormComponentProps } from 'antd/es/form';
import { Dispatch } from 'redux';
import { StateType } from './model';
import { TableListItem, TableListPagination, TableListParams, FormItem } from './data.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './style.less';
import StandardTable, { StandardTableColumnProps } from '@/components/StandardTable';
import { SorterResult } from 'antd/es/table';
import { connect } from 'dva';
import Constants from '../policyInsurance/utils/Constants';
import moment from 'moment';
import PolicyInsuranceForm from './components/policyInsuranceForm';

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  policyInsurance: StateType;
}

interface TableListState {
  modalVisible: boolean;
  selectedRows: TableListItem[];
  formValues: Partial<FormItem>;
  disabled: boolean;
  showDetail: boolean;
}

// const getValue = (obj: { [x: string]: string[] }) =>
//   Object.keys(obj)
//     .map(key => obj[key])
//     .join(',');

@connect(
  ({
    policyInsurance,
    loading,
    global,
  }: {
    policyInsurance: StateType;
    global: StateType;
    loading: {
      models: {
        [key: string]: boolean;
      };
    };
  }) => ({
    policyInsurance,
    global,
    loading: loading.models.policyInsurance,
  }),
)
class TableList extends Component<TableListProps, TableListState> {

  state: TableListState = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    disabled: false,
    showDetail: true
  };

  columns: StandardTableColumnProps[] = [
    {
      title: '申请单号',
      dataIndex: 'id',
      render: (val: string) => <span>{`ZBT-WS-INSURANCE-POLICY-${val}`}</span>,
    },
    {
      title: '被保险人',
      dataIndex: 'receiver',
    },
    {
      title: '品名',
      dataIndex: 'productName',
    },
    {
      title: '数量',
      dataIndex: 'packNum',
    },
    {
      title: '发票金额',
      dataIndex: 'amount',
    },
    {
      title: '保险金额',
      dataIndex: 'insuredAmount',
    },
    {
      title: '保险费',
      dataIndex: 'premium',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (val: string) => <span>{Constants.STATUS[val]}</span>
    },
    {
      title: '申请时间',
      dataIndex: 'createtime',
      render: (val: string) => <span>{moment(val).format('YYYY-MM-DD')}</span>,
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <span style={{ display: record.status === '1' ? 'inline-bloc' : 'none' }}>
            <a onClick={() => message.info('我们将专人联系您完成保单支付等后续事宜，请耐心等待!')}>付款</a>
            <Divider type="vertical" />
          </span>
          <span style={{ display: record.status === '4' ? 'inline-bloc' : 'none' }}>
            <a onClick={() => message.info('保单在线下载待完善!')}>保单下载</a>
            <Divider type="vertical" />
          </span>
          <a onClick={() => this.handleUpdateModalVisible(true, record, true)}>详情</a>
          <Divider type="vertical" />
        </Fragment>
      ),
    },
  ];

  handleModalVisible = (flag?: boolean, record?: TableListItem) => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleSelectRows = (rows: TableListItem[]) => {
    this.setState({
      selectedRows: rows,
    });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'policyInsurance/fetch',
      payload: {
        page: Constants.DEFAULT_PAGE.page,
        size: Constants.DEFAULT_PAGE.size
      }
    });
  }

  handleStandardTableChange = (pagination: Partial<TableListPagination>, filtersArg: Record<keyof TableListItem, string[]>, sorter: SorterResult<TableListItem>) => {
    const { dispatch } = this.props;

    // const filters = Object.keys(filtersArg).reduce((obj, key) => {
    //   const newObj = { ...obj };
    //   newObj[key] = getValue(filtersArg[key]);
    //   return newObj;
    // }, {});

    const params: Partial<TableListParams> = {
      page: pagination.current,
      size: pagination.pageSize
    };
    // if (sorter.field) {
    //   params.sorter = `${sorter.field}_${sorter.order}`;
    // }

    dispatch({
      type: 'policyInsurance/fetch',
      payload: params,
    });
  };

  handleUpdateModalVisible = (flag?: boolean, record?: Partial<TableListItem>, disabled?: boolean) => {
    this.setState({ modalVisible: !!flag, formValues: {}, disabled: !!disabled });
    if (record) {
      const { dispatch } = this.props;
      dispatch({
        type: 'policyInsurance/get', payload: {
          id: record.id,
          onSuccess: (data?: Partial<FormItem>) => {
            this.setState({ formValues: data || {}, disabled: !!disabled });
          }
        }
      });
    }
  };

  handleSave = (fields: FormItem) => {
    const { dispatch } = this.props;
    fields.slgDate = moment(fields.slgDate.toString()).format('YYYY-MM-DD');
    fields.signDate = moment(fields.signDate.toString()).format('YYYY-MM-DD');
    dispatch({
      type: 'policyInsurance/add',
      payload: {
        ...fields,
        onSuccess: () => {
          this.handleUpdateModalVisible();
          const { dispatch } = this.props;
          dispatch({
            type: 'policyInsurance/fetch',
            payload: {
              page: Constants.DEFAULT_PAGE.page,
              size: Constants.DEFAULT_PAGE.size
            }
          });
        }
      },
    });
  };

  render() {

    const { policyInsurance: { data }, loading } = this.props;

    const { selectedRows, modalVisible, formValues, disabled, showDetail } = this.state;

    const methods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleSave: this.handleSave,
    };

    return (
      <PageHeaderWrapper content={
        <div>
          <Button key="detail" type="primary" onClick={() => this.setState({ showDetail: !showDetail })}>{showDetail ? "收起" : "展开说明"}</Button>
          <div style={{ display: showDetail ? 'block' : 'none', marginTop: 10 }}>
            <div>
              <b>产品说明</b><br />
              1、投保货运险需要您填写如下保单信息；<br />
              2、保单受益人请反复核对，我们将根据您填写的信息为您投保。
            </div>
            <br />
            <div>
              <b>投保说明</b><br />
              1、填写投保单后，不可取消。<br />
              2、裸装金属和设备自动剔除刮擦，锈损，凹瘪责任。<br />
              3、电子保单和纸质保单效率一样，尽量使用电子保单。<br />
              4、如果是非集装箱船一定要备注非集装箱，散货船/整船运输的请注明船龄，货物放在舱内还是舱面。<br />
              5、有特殊要求，请在投保前联系在线客服确认是否能操作；如保单号生成后提出无法满足的特殊要求，不予办理，且需承担全额保费。<br />
              6、常见无法满足的特殊要求，如：保单上显示保险费金额。
            </div>
            <br />
            <div>
              <b>投保说明</b><br />
              (如果做信用证注明信用证对保险条款的要求),如果没有特殊注明，则默认为一切险。
            </div>
          </div>
        </div>
      }>
        <Card bordered={false}>
          {
            modalVisible ?
              <PolicyInsuranceForm
                {...methods}
                data={formValues}
                disabled={disabled}
              /> :
              <div className={styles.tableList}>
                <div className={styles.tableListOperator}>
                  <Button icon="plus" type="primary" onClick={() => this.handleUpdateModalVisible(true)}>立即申请</Button>
                </div>
                <StandardTable
                  selectedRows={selectedRows}
                  loading={loading}
                  data={data}
                  columns={this.columns}
                  onSelectRow={this.handleSelectRows}
                  onChange={this.handleStandardTableChange}
                />
              </div>
          }

        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
